package com.example.bgxqgetway.filter;

import com.example.bgxqgetway.util.LogUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

@Slf4j
@Component
public class LogRecodePostFilter extends ZuulFilter {

  @Override
  public String filterType() {
    return FilterConstants.POST_TYPE;
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String path = request.getServletPath();
    log.info(LogUtil.getMessage("path:"+path));
    Map<String, String[]> parameterMap = request.getParameterMap();
    StringBuilder stringBuilder =new StringBuilder();
    stringBuilder.append("{");
    if(parameterMap!=null){
      parameterMap.forEach((key,value)->{
        stringBuilder.append(key).append(":");
        for (String s : value) {
          stringBuilder.append(s).append(",");
        }
      });
    }
    stringBuilder.append("}");
    log.info(LogUtil.getMessage("request:"+stringBuilder));
    InputStream responseDataStream = ctx.getResponseDataStream();
    try {
      String response = StreamUtils.copyToString(responseDataStream, StandardCharsets.UTF_8);
      log.info(LogUtil.getMessage("result:"+response));
      ctx.setResponseBody(response);
      ctx.getResponse().setCharacterEncoding("utf-8");
    } catch (IOException e) {
      log.error(e.getMessage());
      log.error(Arrays.toString(e.getStackTrace()));
    }
    return null;
  }
}
